﻿using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Client.Forms
{
    public partial class newsForm : Form
    {
        DataCenter.Models.IInfo stockInfo = null;
        public int page
        {
            get { return _page; }
            set
            {
                _page = value;
                GetGGNewsList();
            }
        }
        int _page = 1;
        List<JToken> newsL;

        public newsForm()
        {
            InitializeComponent();
        }


        //private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
        //{
        //    if (newsL == null)
        //        return;

        //    Graphics gfx = e.Graphics;
        //    string dtext = (string)listBox1.Items[e.Index];

        //    Rectangle rect = new Rectangle(16, 22, this.listBox1.ClientSize.Width - 16, e.ItemHeight);
        //    StringFormat stf = new StringFormat();
        //    stf.FormatFlags = StringFormatFlags.FitBlackBox;
        //    SizeF f2 = gfx.MeasureString(dtext, listBox1.Font, rect.Width, stf);
        //    int Temp = e.ItemWidth;

        //    if (f2.Width < (16))
        //        Temp = 16+ 4;//行间距

        //    e.ItemHeight = 22+ (int)f2.Height + 16;//上下高度
        //}

        //private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        //{
        //    if (newsL== null)
        //        return;

        //    string dtext = (string)listBox1.Items[e.Index];


        //    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        //    {
        //        Graphics gfx = e.Graphics;

        //        Pen pen = new Pen(Brushes.SteelBlue, 0.4f);

        //        gfx.DrawRectangle(pen, e.Bounds.X + 4, e.Bounds.Y + 4, e.Bounds.Width - 8, e.Bounds.Height - 8);
        //        gfx.FillRectangle(Brushes.LightSteelBlue, e.Bounds.X + 5, e.Bounds.Y + 5, e.Bounds.Width - 9, e.Bounds.Height - 9);

        //        Rectangle rect = new Rectangle(e.Bounds.X + 16, e.Bounds.Y + 22, this.listBox1.ClientSize.Width - 16, this.ClientSize.Height);
        //        StringFormat stf = new StringFormat();
        //        stf.FormatFlags = StringFormatFlags.FitBlackBox;

        //        gfx.DrawString(dtext, listBox1.Font, Brushes.Black, rect, stf);
        //    }
        //    else
        //    {
        //        Graphics gfx = e.Graphics;
        //        gfx.FillRectangle(Brushes.White, e.Bounds.X + 4, e.Bounds.Y + 4, e.Bounds.Width - 7, e.Bounds.Height - 7);
        //        gfx.FillRectangle(Brushes.SteelBlue, e.Bounds.X + 4, e.Bounds.Y + e.Bounds.Height - 8, e.Bounds.Width - 8, 1);
        //        Pen pen = new Pen(Brushes.SteelBlue, 0.4f);

        //        Rectangle rect = new Rectangle(e.Bounds.X + 16, e.Bounds.Y + 22, this.listBox1.ClientSize.Width - 16, this.ClientSize.Height);
        //        StringFormat stf = new StringFormat();
        //        stf.FormatFlags = StringFormatFlags.FitBlackBox;
        //        gfx.DrawString(dtext, listBox1.Font, Brushes.Black, rect, stf);
        //    }
        //    e.DrawFocusRectangle();
        //}

        private async void listBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                if (listBox1.SelectedIndex != -1)
                {
                    try
                    {
                        string id = (string)newsL[listBox1.SelectedIndex]["id"];
                        string url = (string)newsL[listBox1.SelectedIndex]["url"];
                        var res = await DataCenter.DataCenter.GetNewsContent(id, url);
                        var html = new HtmlAgilityPack.HtmlDocument();
                        html.LoadHtml(res);
                        string temp = "";
                        foreach (var i in html.DocumentNode.SelectNodes("//p"))
                        {
                            string str = i.InnerText;
                            if (str != "" && !Regex.IsMatch(str, "^图片来源：(?=.+)") && !Regex.IsMatch(str, "(?<=^.+)版权所有，"))
                            {
                                if (str == "近期原创文章")
                                    break;
                                temp += str + "\r\n";
                            }
                        }
                        textBox1.Text = "";
                        textBox1.Focus();
                        textBox1.Text = temp;
                    }
                    catch (DataCenter.MyException.APIReturnException ex)
                    {
                        var l = ex.Message.Split('~');
                        if (l[0] == "1000")
                            Utility.ShowLoginAgain();
                        throw;
                    }
                }
            }
        }

        void GetGGNewsList()
        {
            JToken jo = DataCenter.DataCenter.GetNewsList(page, stockInfo.symbol);
            List<JToken> l = new List<JToken>();
            foreach (JObject j in jo)
            {
                l.Add(j);
                listBox1.Items.Add(j["title"] + "\r\n【" + j["time"] + "】");
            }
            newsL = l;
        }

        void GetZhishuNewsList()
        {
            var ja = DataCenter.DataCenter.GetNewsList(page);
            var newsL = SortNews((JArray)ja);
            foreach (var j in newsL)
            {
                listBox1.Items.Add(j["title"] + "\r\n【" + j["time"] + "】");
            }
            this.newsL = newsL;
        }

        List<JToken> SortNews(JArray ja)
        {
            List<JToken> l = new List<JToken>();
            //将数据添加到列表
            for (int i = 0; i < ja[0].Count(); i++)
            {
                for (int k = 0; k < ja.Count; k++)
                {
                    l.Add(ja[k][i]);
                }
            }

            //用插入排序把数据按照时间顺序排好
            for (int i = 1; i < l.Count; i++)
            {
                var insertVal = l[i];
                int insertIndex = i - 1;
                int ts1 = int.Parse((string)insertVal["predictTimestamp"]);
                while (insertIndex >= 0)
                {
                    if (l[insertIndex] != null)
                    {
                        int ts2 = int.Parse((string)l[insertIndex]["predictTimestamp"]);
                        if (ts1 > ts2)   //这里小于是升序，大于是降序
                            l[insertIndex + 1] = l[insertIndex];
                        else if (ts1 == ts2)
                            l[insertIndex + 1] = null;
                        else
                            break;
                    }
                    insertIndex--;
                }
                l[insertIndex + 1] = insertVal;
            }

            //去除标题相同的项目
            LinkedList<JToken> tmpL = new LinkedList<JToken>();
            tmpL.AddLast(l[0]);
            for (int i = 1; i < l.Count; i++)
            {
                if (l[i] == null)
                    continue;
                string title = (string)l[i]["title"];
                bool exait = false;
                foreach (var j in tmpL)
                {
                    if (title == (string)j["title"])
                    {
                        exait = true;
                        break;
                    }
                }
                if (!exait)
                    tmpL.AddLast(l[i]);
            }

            return tmpL.ToList();
        }

        public void ShowForm(DataCenter.Models.IInfo info)
        {
            textBox1.Text = "";
            listBox1.Items.Clear();
            stockInfo = info;
            if (info == null)
            {
                this.Text = "市场资讯";
                GetZhishuNewsList();
            }
            else
            {
                this.Text = stockInfo.name + " - 个股新闻";
                GetGGNewsList();
            }
            this.Show();
            listBox1.Focus();
        }

        private void newsForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Managers.Manager.newsForm = null;
        }
    }
}
